package com.ssy.lingxi.member.merchant.serviceimpl.web;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.basic.PlatformRuleTypeEnum;
import com.ssy.lingxi.common.constant.basic.PurchaseContractPayTypeEnum;
import com.ssy.lingxi.common.constant.member.BusinessCategoryInvoiceTypeEnum;
import com.ssy.lingxi.common.constant.member.MemberLevelTypeEnum;
import com.ssy.lingxi.common.constant.member.MemberStatusEnum;
import com.ssy.lingxi.common.constant.member.MemberTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.constant.MemberRelationTypeEnum;
import com.ssy.lingxi.member.merchant.api.model.constant.MemberProcessTypeEnum;
import com.ssy.lingxi.member.merchant.config.ServiceConfig;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.bo.FileBO;
import com.ssy.lingxi.member.merchant.model.bo.WorkflowTaskListBO;
import com.ssy.lingxi.member.merchant.model.constant.*;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.ProvinceCodeVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.UpperRelationIdVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.*;
import com.ssy.lingxi.member.merchant.model.vo.validate.request.*;
import com.ssy.lingxi.member.merchant.model.vo.validate.response.*;
import com.ssy.lingxi.member.merchant.repository.BaseMemberRuleRepository;
import com.ssy.lingxi.member.merchant.repository.MemberInspectRepository;
import com.ssy.lingxi.member.merchant.repository.MemberRelationRepository;
import com.ssy.lingxi.member.merchant.repository.MemberUserRepository;
import com.ssy.lingxi.member.merchant.service.base.*;
import com.ssy.lingxi.member.merchant.service.feign.IWorkflowFeignService;
import com.ssy.lingxi.member.merchant.service.web.IMemberAbilityDepositService;
import com.ssy.lingxi.member.merchant.service.web.IMemberProcessRuleService;
import com.ssy.lingxi.member.merchant.utils.AgentAreaUtil;
import com.ssy.lingxi.member.merchant.utils.NumberUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 会员能力 - 会员审核入库、资料变更相关接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-05-19
 */
@Service
public class MemberAbilityDepositServiceImpl implements IMemberAbilityDepositService {
    @Resource
    private IBaseMemberCacheService memberCacheService;

    @Resource
    private MemberRelationRepository relationRepository;

    @Resource
    private MemberUserRepository memberUserRepository;

    @Resource
    private MemberInspectRepository memberInspectRepository;

    @Resource
    private BaseMemberRuleRepository baseMemberRuleRepository;

    @Resource
    private IBaseMemberRegisterDetailService baseMemberRegisterDetailService;

    @Resource
    private IBaseMemberDepositDetailService baseMemberDepositDetailService;

    @Resource
    private IBaseMemberQualificationService baseMemberQualificationService;

    @Resource
    private IBaseMemberClassificationService baseMemberClassificationService;

    @Resource
    private IWorkflowFeignService workflowFeignService;

    @Resource
    private IMemberProcessRuleService memberProcessRuleService;

    @Resource
    private IBaseMemberHistoryService baseMemberHistoryService;

    @Resource
    private IBaseMemberValidateService baseMemberValidateService;

    @Resource
    private IBaseCountryAreaService baseCountryAreaService;


    /**
     * 获取会员审核入库各个步骤分页查询列表页面下拉框
     *
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberDepositSearchConditionVO> getDepositPageConditions(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //规则：
        // 1). 上级会员角色为企业会员，下级会员角色为企业会员：无限制
        // 2). 上级会员角色为企业会员，下级会员角色为渠道会员：不允许创建
        // 3). 上级会员角色为渠道会员，下级会员角色为企业会员：不允许创建
        // 4). 上级会员角色为渠道会员，下级会员角色为渠道会员：判断下级会员是否有另一个服务消费者角色在关系树中

        MemberDepositSearchConditionVO conditionVO = new MemberDepositSearchConditionVO();
        //会员类型（这里返回的是Id）
        List<MemberTypeIdAndNameVO> memberTypeList = baseMemberValidateService.getSubMemberTypeList(loginUser.getMemberType());
        memberTypeList.add(0, new MemberTypeIdAndNameVO(0L, MemberStringEnum.ALL.getName()));
        conditionVO.setMemberTypes(memberTypeList);

        //会员角色（按照Id升序排序）
        List<RoleIdAndNameVO> roleList = baseMemberValidateService.getSubRoleList(loginUser.getMemberType());
        roleList.add(0, new RoleIdAndNameVO(0L, MemberStringEnum.ALL.getName()));
        conditionVO.setRoles(roleList);

        //申请来源
        List<DropdownItem> itemList = MemberRegisterSourceEnum.toList().stream().map(s -> new DropdownItem(s, MemberRegisterSourceEnum.getCodeMessage(s))).collect(Collectors.toList());
        conditionVO.setSources(itemList);
        return Wrapper.success(conditionVO);
    }

    /**
     * 分页查询“待审核入库资料”会员列表
     *
     * @param headers Http头部新
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDepositPageQueryVO>> pageToVerifyDepositoryDetail(HttpHeaders headers, MemberDepositPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return pageValidateRelations(MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_DETAIL, loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getName(), pageVO.getMemberTypeId(), pageVO.getRoleId(), pageVO.getSource(), pageVO.getCurrent(), pageVO.getPageSize());
    }

    /**
     * “待审核入库资料” - 查询会员详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberToVerifyDepositDetailVO> getToVerifyDepositoryDetail(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberRelationDO relationDO = relationRepository.findById(idVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        if(relationDO.getValidateTask() == null || !StringUtils.hasLength(relationDO.getValidateTask().getProcessKey()) || !StringUtils.hasLength(relationDO.getValidateTask().getTaskId()) || !relationDO.getValidateTask().getProcessTypeEnum().equals(MemberProcessTypeEnum.MEMBER_DEPOSITORY.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MC_MEMBER_PROCESS_DATA_ERROR);
        }

        Wrapper<WorkflowTaskListBO> result = workflowFeignService.listMemberProcessSteps(loginUser.getMemberId(), relationDO.getValidateTask().getProcessKey(), relationDO.getValidateTask().getTaskId());
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        MemberToVerifyDepositDetailVO detailVO = new MemberToVerifyDepositDetailVO();
        detailVO.setOuterVerifySteps(baseMemberValidateService.getMemberDepositOuterSteps(loginUser.getMemberRoleName(), relationDO.getSubRoleName()));
        detailVO.setCurrentOuterStep(2);

        detailVO.setInnerVerifySteps(result.getData().getStepList());
        detailVO.setCurrentInnerStep(result.getData().getCurrentStep());

        detailVO.setMemberId(relationDO.getSubMemberId());
        detailVO.setValidateId(relationDO.getId());
        detailVO.setName(relationDO.getSubMember().getName());
        detailVO.setStatus(relationDO.getStatus());
        detailVO.setStatusName(MemberStatusEnum.getCodeMessage(relationDO.getStatus()));
        detailVO.setInnerStatus(relationDO.getInnerStatus());
        detailVO.setInnerStatusName(MemberInnerStatusEnum.getCodeMsg(relationDO.getInnerStatus()));
        detailVO.setOuterStatus(relationDO.getOuterStatus());
        detailVO.setOuterStatusName(MemberOuterStatusEnum.getCodeMsg(relationDO.getOuterStatus()));
        detailVO.setMemberTypeEnum(relationDO.getSubMemberTypeEnum());
        detailVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubMemberTypeEnum()));
        detailVO.setRoleName(relationDO.getSubRoleName());
        detailVO.setLevel(relationDO.getLevelRight() == null ? 0 : relationDO.getLevelRight().getLevel());
        detailVO.setLevelTag(relationDO.getLevelRight() == null ? "" : relationDO.getLevelRight().getLevelTag());
        detailVO.setAccount(relationDO.getSubMember().getAccount());
        detailVO.setPhone(relationDO.getSubMember().getPhone());
        detailVO.setEmail(relationDO.getSubMember().getEmail());
        detailVO.setRegisterTime(relationDO.getCreateTime().format(ServiceConfig.DEFAULT_DATETIME_FORMATTER));

        //渠道信息
        if(relationDO.getSubMemberLevelTypeEnum().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
            detailVO.setUpperRelationId(relationDO.getChannel().getAgentArea().getUpperRelationId());
            detailVO.setUpperMembers(baseMemberValidateService.getUpperRelationList(loginUser.getMemberId(), loginUser.getMemberRoleId()));
            detailVO.setChannelLevelTag(relationDO.getChannel().getChannelLevelTag());
            detailVO.setChannelTypeId(relationDO.getChannel().getChannelType().getId());
            detailVO.setChannelTypes(baseMemberValidateService.getChannelTypes());
            detailVO.setAreaCodes(AgentAreaUtil.transferToCodeList(relationDO.getChannel().getAgentArea()));
            detailVO.setRemark(relationDO.getChannel().getRemark());

        } else {
            detailVO.setUpperRelationId(0L);
            detailVO.setUpperMembers(Stream.of(new UpperRelationIdAndNameVO(0L, "")).collect(Collectors.toList()));
            detailVO.setChannelLevelTag("");
            detailVO.setChannelTypeId(0L);
            detailVO.setAreaCodes(new ArrayList<>());
            detailVO.setUpperRelationId(0L);
            detailVO.setRemark("");
        }

        //注册资料（平台审核通过后，将注册资料的版本设置为“Using"）
        detailVO.setRegisterDetails(baseMemberRegisterDetailService.groupMemberRegisterDetailText(relationDO.getSubMember(), MemberDetailVersionEnum.USING));
        //入库资料
        detailVO.setDepositDetails(baseMemberDepositDetailService.groupMemberDepositoryDetail(relationDO));
        detailVO.setDepositDetailTexts(baseMemberDepositDetailService.findMemberDepositoryDetailText(relationDO, MemberDetailVersionEnum.TO_BE_VALIDATE));
        //资质证明文件
        detailVO.setQualities(baseMemberQualificationService.findMemberQualities(relationDO));
        //内、外部历史记录
        detailVO.setInnerHistory(baseMemberHistoryService.listMemberInnerHistory(relationDO));
        detailVO.setOuterHistory(baseMemberHistoryService.listMemberOuterHistory(relationDO));

        return Wrapper.success(detailVO);
    }

    /**
     * “待审核入库资料” - 根据选择的上级会员查询省列表
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<CountryAreaCodeNameVO>> getProvinceList(HttpHeaders headers, UpperRelationIdVO idVO) {
        memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.getProvinceList(idVO.getUpperRelationId());
    }

    /**
     * “待审核入库资料” - 根据选择的上级会员查询省列表
     *
     * @param headers  Http头部信息
     * @param citiesVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<CountryAreaCodeNameVO>> getCityList(HttpHeaders headers, MemberDepositGetCitiesVO citiesVO) {
        memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.getCityList(citiesVO.getUpperRelationId(), citiesVO.getProvinceCode());
    }

    /**
     * “待审核入库资料” - 审核会员
     *
     * @param headers   Http头部信息
     * @param depositVO 接口参数
     * @return 审核结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> toVerifyDepositoryDetail(HttpHeaders headers, MemberToVerifyDepositVO depositVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberRelationDO relationDO = relationRepository.findById(depositVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //检查入库状态
        if(!relationDO.getInnerStatus().equals(MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_DETAIL.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_VALIDATE_STATUS_INCORRECT);
        }

        //审核不通过的原因不能为空
        if(depositVO.getAgree().equals(MemberValidateAgreeEnum.DISAGREE.getCode()) && !StringUtils.hasLength(depositVO.getReason())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_VALIDATE_DISAGREE_REASON_CAN_NOT_BE_EMPTY);
        }

        //检查入库资料
        Wrapper<Void> depositResult = baseMemberDepositDetailService.checkAndSaveMemberDepositoryDetail(relationDO, depositVO.getDepositDetails());
        if(depositResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(depositResult.getCode(), depositResult.getMessage());
        }

        //如果是渠道会员
        if(relationDO.getSubMemberLevelTypeEnum().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
            //检查区域，并保存新的代理
            Wrapper<Void> channelResult = baseMemberValidateService.checkAndUpdateChannelAgentAreas(relationDO, depositVO.getUpperRelationId(), depositVO.getChannelTypeId(), depositVO.getAreaCodes(), depositVO.getRemark());
            if(channelResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(channelResult.getCode(), channelResult.getMessage());
            }
        }

        //检查并保存资质文件
        Wrapper<Void> qualityResult = baseMemberQualificationService.checkAndSaveMemberQualities(relationDO, depositVO.getQualities());
        if(qualityResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(qualityResult.getCode(), qualityResult.getMessage());
        }

        //执行工作流任务
        Wrapper<Void> taskResult = baseMemberValidateService.execMemberProcess(loginUser, relationDO, depositVO.getAgree(), depositVO.getReason(), MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_DETAIL);
        if(taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }

        return Wrapper.success();
    }

    /**
     * “待审核入库资料” - 批量审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> batchVerifyDepositoryDetail(HttpHeaders headers, ValidateIdsVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        List<MemberRelationDO> relationList = relationRepository.findAllById(idVO.getValidateIds());
        if(idVO.getValidateIds().size() != relationList.size()) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //查询批量审核中，是否已经配置了入库资料的角色，如果有，返回提示
        List<RoleDO> subRoles = relationList.stream().map(MemberRelationDO::getSubRole).collect(Collectors.toList());
        if(memberProcessRuleService.existDepositoryConfig(loginUser.getMemberId(), loginUser.getMemberRoleId(), subRoles)) {
            return Wrapper.fail(ResponseCode.MC_MS_CAN_NOT_BATCH_VALIDATE_CAUSE_OF_DEPOSIT_CONFIG_NOT_EMPTY);
        }

        return baseMemberValidateService.batchExecMemberProcess(loginUser, idVO.getValidateIds(), MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_DETAIL);
    }

    /**
     * 分页查询“待审核入库资质”会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDepositPageQueryVO>> pageToVerifyDepositoryQualification(HttpHeaders headers, MemberDepositPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return pageValidateRelations(MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_QUALIFICATION, loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getName(), pageVO.getMemberTypeId(), pageVO.getRoleId(), pageVO.getSource(), pageVO.getCurrent(), pageVO.getPageSize());
    }

    /**
     * “待审核入库资质” - 查询会员详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberDepositDetailVO> getToVerifyDepositoryQualification(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return getValidateMemberDetails(idVO.getValidateId(), loginUser);
    }

    /**
     * “待审核入库资质” - 审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> toVerifyDepositoryQualification(HttpHeaders headers, ValidateAgreeVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.execMemberProcess(loginUser, idVO.getValidateId(), idVO.getAgree(), idVO.getReason(), MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_QUALIFICATION);
    }

    /**
     * “待审核入库资质” - 批量审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> batchVerifyDepositoryQualifications(HttpHeaders headers, ValidateIdsVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.batchExecMemberProcess(loginUser, idVO.getValidateIds(), MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_QUALIFICATION);
    }

    /**
     * 分页查询“待入库考察”会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDepositPageQueryVO>> pageToInspectDepository(HttpHeaders headers, MemberDepositPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return pageValidateRelations(MemberInnerStatusEnum.TO_INSPECT_DEPOSITORY, loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getName(), pageVO.getMemberTypeId(), pageVO.getRoleId(), pageVO.getSource(), pageVO.getCurrent(), pageVO.getPageSize());
    }

    /**
     * “待入库考察” - 查询会员详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberDepositDetailVO> getToInspectDepository(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return getValidateMemberDetails(idVO.getValidateId(), loginUser);
    }

    /**
     * “待入库考察” - 审核
     *
     * @param headers Http头部信息
     * @param depositVO    接口参数
     * @return 查询结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> toInspectDepository(HttpHeaders headers, MemberToInspectDepositVO depositVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberRelationDO relationDO = relationRepository.findById(depositVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        MemberUserDO userDO = memberUserRepository.findById(loginUser.getUserId()).orElse(null);
        if(userDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_DOES_NOT_EXIST);
        }

        MemberInspectDO memberInspectDO = new MemberInspectDO();
        memberInspectDO.setCreateTime(LocalDateTime.now());
        memberInspectDO.setInspectTime(LocalDateTime.parse(depositVO.getInspectDay().concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        memberInspectDO.setSource(MemberInspectSourceEnum.BY_MEMBER_PROCESS.getCode());
        memberInspectDO.setMemberId(loginUser.getMemberId());
        memberInspectDO.setRoleId(loginUser.getMemberRoleId());
        memberInspectDO.setSubMember(relationDO.getSubMember());
        memberInspectDO.setSubRoleId(relationDO.getSubRoleId());
        memberInspectDO.setSubject(relationDO.getSubMember().getName().concat("入库考察"));
        memberInspectDO.setInspectType(MemberInspectTypeEnum.deposit.getCode());
        memberInspectDO.setByUser(userDO);
        memberInspectDO.setReason("");
        memberInspectDO.setAttachments(new ArrayList<>());
        memberInspectDO.setScore(depositVO.getScore());
        memberInspectDO.setResult(depositVO.getResult());
        memberInspectDO.setReports(CollectionUtils.isEmpty(depositVO.getReports()) ? new ArrayList<>() : depositVO.getReports().stream().map(fileUploadVO -> new FileBO(fileUploadVO.getName(), fileUploadVO.getUrl())).collect(Collectors.toList()));
        memberInspectRepository.saveAndFlush(memberInspectDO);

        return baseMemberValidateService.execMemberProcess(loginUser, relationDO, depositVO.getAgree(), depositVO.getReason(), MemberInnerStatusEnum.TO_INSPECT_DEPOSITORY);
    }

    /**
     * 分页查询“待入库分类”会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDepositPageQueryVO>> pageToClassifyDepository(HttpHeaders headers, MemberDepositPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return pageValidateRelations(MemberInnerStatusEnum.TO_CLASSIFY_DEPOSITORY, loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getName(), pageVO.getMemberTypeId(), pageVO.getRoleId(), pageVO.getSource(), pageVO.getCurrent(), pageVO.getPageSize());
    }

    /**
     * “待入库分类” - 查询会员详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberToClassifyDetailVO> getToClassifyDepository(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberRelationDO relationDO = relationRepository.findById(idVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        return getToClassifyDetails(loginUser, relationDO);
    }

    /**
     * “待入库分类” - “适用区域”-省列表
     *
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<CountryAreaCodeNameVO>> getToClassifyProvinces(HttpHeaders headers) {
        return baseCountryAreaService.listAllProvince();
    }

    /**
     * “待入库分类” - “适用区域”-根据省编码查询市列表
     *
     * @param headers Http头部信息
     * @param codeVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<CountryAreaCodeNameVO>> getToClassifyCities(HttpHeaders headers, ProvinceCodeVO codeVO) {
        return baseCountryAreaService.listAllCitiesByProvinceCode(codeVO.getProvinceCode());
    }

    /**
     * “待入库分类” - 品类信息 - 查询结算方式与发票类型
     *
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberClassifyCategoryItemVO> getToClassifyCategoryItems(HttpHeaders headers) {
        MemberClassifyCategoryItemVO itemVO = new MemberClassifyCategoryItemVO();
        itemVO.setPayTypes(baseMemberRuleRepository.findByRuleTypeAndStatus(PlatformRuleTypeEnum.PURCHASE_CONTRACT.getCode(), EnableDisableStatus.ENABLE.getCode()).stream().map(baseMemberRule -> new BusinessCategoryPayTypeVO(baseMemberRule.getMethodCode(), PurchaseContractPayTypeEnum.getNameByCode(baseMemberRule.getMethodCode()))).sorted(Comparator.comparingInt(BusinessCategoryPayTypeVO::getPayType)).collect(Collectors.toList()));
        itemVO.setInvoiceTypes(Arrays.stream(BusinessCategoryInvoiceTypeEnum.values()).map(e -> new BusinessCategoryInvoiceTypeVO(e.getCode(), e.getName())).sorted(Comparator.comparingInt(BusinessCategoryInvoiceTypeVO::getInvoiceType)).collect(Collectors.toList()));
        itemVO.setCurrencyTypes(Arrays.stream(CurrencyTypeEnum.values()).map(e -> new BusinessCurrencyTypeVO(e.getCode(), e.getMsg())).sorted(Comparator.comparingInt(BusinessCurrencyTypeVO::getCurrencyType)).collect(Collectors.toList()));
        itemVO.setSettlementDocuments(Arrays.stream(SettlementDocumentsEnum.values()).map(e -> new BusinessSettlementDocumentsTypeVO(e.getCode(), e.getMsg())).sorted(Comparator.comparingInt(BusinessSettlementDocumentsTypeVO::getSettlementDocumentsType)).collect(Collectors.toList()));
        itemVO.setPaymentTypes(Arrays.stream(PaymentTypeEnum.values()).map(e -> new BusinessPaymentTypeVO(e.getCode(), e.getMsg())).sorted(Comparator.comparingInt(BusinessPaymentTypeVO::getPaymentType)).collect(Collectors.toList()));
        itemVO.setAdvanceCharges(Arrays.stream(AdvanceChargeEnum.values()).map(e -> new BusinessAdvanceChargeTypeVO(e.getCode(), e.getMsg())).sorted(Comparator.comparingInt(BusinessAdvanceChargeTypeVO::getAdvanceChargeType)).collect(Collectors.toList()));
        return Wrapper.success(itemVO);
    }

    /**
     * “待入库分类” - 审核
     *
     * @param headers Http头部信息
     * @param depositVO    接口参数
     * @return 查询结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> toClassifyDepository(HttpHeaders headers, MemberToClassifyDepositVO depositVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberRelationDO relationDO = relationRepository.findById(depositVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //检查并保存入库分类信息
        Wrapper<Void> saveResult = baseMemberClassificationService.saveMemberClassification(relationDO, depositVO.getRemark(), depositVO.getCurrencyType(), depositVO.getCode(), depositVO.getPartnerType(), depositVO.getMaxAmount(), depositVO.getAreaCodes(), depositVO.getCategories());
        if(saveResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(saveResult.getCode(), saveResult.getMessage());
        }

        return baseMemberValidateService.execMemberProcess(loginUser, relationDO, depositVO.getAgree(), depositVO.getReason(), MemberInnerStatusEnum.TO_CLASSIFY_DEPOSITORY);
    }

    /**
     * 分页查询“待审核入库(一级)”会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDepositPageQueryVO>> pageToDepositGradeOne(HttpHeaders headers, MemberDepositPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return pageValidateRelations(MemberInnerStatusEnum.TO_DEPOSIT_GRADE_ONE, loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getName(), pageVO.getMemberTypeId(), pageVO.getRoleId(), pageVO.getSource(), pageVO.getCurrent(), pageVO.getPageSize());
    }

    /**
     * “待审核入库(一级)” - 查询会员详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberDepositGradeDetailVO> getToDepositGradeOne(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberRelationDO relationDO = relationRepository.findById(idVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }
        return getDepositGradeDetails(loginUser, relationDO);
    }

    /**
     * “待审核入库(一级)” - 审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> toDepositGradeOne(HttpHeaders headers, ValidateAgreeVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.execMemberProcess(loginUser, idVO.getValidateId(), idVO.getAgree(), idVO.getReason(), MemberInnerStatusEnum.TO_DEPOSIT_GRADE_ONE);
    }

    /**
     * “待审核入库(一级)” - 批量审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> batchDepositGradeOne(HttpHeaders headers, ValidateIdsVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.batchExecMemberProcess(loginUser, idVO.getValidateIds(), MemberInnerStatusEnum.TO_DEPOSIT_GRADE_ONE);
    }

    /**
     * 分页查询“待审核入库(二级)”会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDepositPageQueryVO>> pageToDepositGradeTwo(HttpHeaders headers, MemberDepositPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return pageValidateRelations(MemberInnerStatusEnum.TO_DEPOSIT_GRADE_TWO, loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getName(), pageVO.getMemberTypeId(), pageVO.getRoleId(), pageVO.getSource(), pageVO.getCurrent(), pageVO.getPageSize());
    }

    /**
     * “待审核入库(二级)” - 查询会员详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberDepositGradeDetailVO> getToDepositGradeTwo(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberRelationDO relationDO = relationRepository.findById(idVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }
        return getDepositGradeDetails(loginUser, relationDO);
    }

    /**
     * “待审核入库(二级)” - 审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> toDepositGradeTwo(HttpHeaders headers, ValidateAgreeVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.execMemberProcess(loginUser, idVO.getValidateId(), idVO.getAgree(), idVO.getReason(), MemberInnerStatusEnum.TO_DEPOSIT_GRADE_TWO);
    }

    /**
     * “待审核入库(二级)” - 批量审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> batchDepositGradeTwo(HttpHeaders headers, ValidateIdsVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.batchExecMemberProcess(loginUser, idVO.getValidateIds(), MemberInnerStatusEnum.TO_DEPOSIT_GRADE_TWO);
    }

    /**
     * 分页查询“待确认入库”会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberDepositPageQueryVO>> pageToConfirmDepository(HttpHeaders headers, MemberDepositPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        List<MemberInnerStatusEnum> innerStatusEnums = Stream.of(
                MemberInnerStatusEnum.DEPOSITORY_DETAIL_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_QUALIFICATION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_INSPECTION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_CLASSIFICATION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_GRADE_ONE_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_GRADE_TWO_NOT_PASSED,
                MemberInnerStatusEnum.TO_CONFIRM_DEPOSITORY).collect(Collectors.toList());
        return pageValidateRelations(innerStatusEnums, loginUser.getMemberId(), loginUser.getMemberRoleId(), pageVO.getName(), pageVO.getMemberTypeId(), pageVO.getRoleId(), pageVO.getSource(), pageVO.getCurrent(), pageVO.getPageSize());
    }

    /**
     * “待确认入库” - 查询会员详情
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberDepositGradeDetailVO> getToConfirmDepository(HttpHeaders headers, ValidateIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberRelationDO relationDO = relationRepository.findById(idVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }
        return getDepositGradeDetails(loginUser, relationDO);
    }

    /**
     * “待确认入库” - 审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> toConfirmDepository(HttpHeaders headers, ValidateAgreeVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        List<MemberInnerStatusEnum> innerStatusEnums = Stream.of(
                MemberInnerStatusEnum.DEPOSITORY_DETAIL_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_QUALIFICATION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_INSPECTION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_CLASSIFICATION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_GRADE_ONE_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_GRADE_TWO_NOT_PASSED,
                MemberInnerStatusEnum.TO_CONFIRM_DEPOSITORY).collect(Collectors.toList());
        return baseMemberValidateService.execMemberProcess(loginUser, idVO.getValidateId(), idVO.getAgree(), idVO.getReason(), innerStatusEnums);
    }

    /**
     * “待确认入库” - 批量审核
     *
     * @param headers Http头部信息
     * @param idVO    接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<Void> batchConfirmDepositories(HttpHeaders headers, ValidateIdsVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        List<MemberInnerStatusEnum> innerStatusEnums = Stream.of(
                MemberInnerStatusEnum.DEPOSITORY_DETAIL_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_QUALIFICATION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_INSPECTION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_CLASSIFICATION_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_GRADE_ONE_NOT_PASSED,
                MemberInnerStatusEnum.DEPOSITORY_GRADE_TWO_NOT_PASSED,
                MemberInnerStatusEnum.TO_CONFIRM_DEPOSITORY).collect(Collectors.toList());
        return baseMemberValidateService.batchExecMemberProcess(loginUser, idVO.getValidateIds(), innerStatusEnums);
    }

    /**
     * （重载）分页查询入库会员列表
     * @param innerStatusEnum 内部状态
     * @param memberId 当前会员Id
     * @param roleId   当前会员角色Id
     * @param subMemberName  下级会员名称
     * @param subMemberTypeId 下级会员会员类型
     * @param subRoleId  下级会员角色Id
     * @param source     会员注册来源
     * @param current    分页参数 - 当前页
     * @param pageSize   分页参数 - 每页行数
     * @return 查询结果
     */
    private Wrapper<PageData<MemberDepositPageQueryVO>> pageValidateRelations(MemberInnerStatusEnum innerStatusEnum, Long memberId, Long roleId, String subMemberName, Long subMemberTypeId, Long subRoleId, Integer source, int current, int pageSize) {
        return pageValidateRelations(Stream.of(innerStatusEnum).collect(Collectors.toList()), memberId, roleId, subMemberName, subMemberTypeId, subRoleId, source, current, pageSize);
    }

    /**
     * 分页查询入库会员列表
     * @param innerStatusEnums 内部状态List
     * @param memberId 当前会员Id
     * @param roleId   当前会员角色Id
     * @param subMemberName  下级会员名称
     * @param subMemberTypeId 下级会员会员类型
     * @param subRoleId  下级会员角色Id
     * @param source     会员注册来源
     * @param current    分页参数 - 当前页
     * @param pageSize   分页参数 - 每页行数
     * @return 查询结果
     */
    private Wrapper<PageData<MemberDepositPageQueryVO>> pageValidateRelations(List<MemberInnerStatusEnum> innerStatusEnums, Long memberId, Long roleId, String subMemberName, Long subMemberTypeId, Long subRoleId, Integer source, int current, int pageSize) {
        Pageable pageable = PageRequest.of(current - 1, pageSize, Sort.by("id").descending());
        Specification<MemberRelationDO> specification = (Specification<MemberRelationDO>) (root, query, criteriaBuilder) -> {
          List<Predicate> list = new ArrayList<>();
          list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), memberId));
          list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), roleId));
          list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));

          if(innerStatusEnums.size() == 1) {
              list.add(criteriaBuilder.equal(root.get("innerStatus").as(Integer.class), innerStatusEnums.get(0).getCode()));
          } else {
              Expression<Integer> exp = root.get("innerStatus");
              list.add(exp.in(innerStatusEnums.stream().map(MemberInnerStatusEnum::getCode).collect(Collectors.toList())));
          }

          //外部状态只能为“入库审核中”
          list.add(criteriaBuilder.equal(root.get("outerStatus").as(Integer.class), MemberOuterStatusEnum.DEPOSITING.getCode()));

          //下级会员名称
          if(StringUtils.hasLength(subMemberName)) {
              Join<MemberRelationDO, MemberDO> subMemberJoin = root.join("subMember", JoinType.LEFT);
              list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + subMemberName.trim() + "%"));
          }

          //下级会员类型
          if(NumberUtil.notNullOrZero(subMemberTypeId)) {
              Join<MemberRelationDO, RoleDO> subRoleJoin = root.join("subRole", JoinType.LEFT);
              list.add(criteriaBuilder.equal(subRoleJoin.get("memberType").get("id").as(Long.class), subMemberTypeId));
          }

          //下级会员角色
          if(NumberUtil.notNullOrZero(subRoleId)) {
              list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), subRoleId));
          }

          //下级会员注册来源
          if(NumberUtil.notNullOrZero(source)) {
              Join<MemberRelationDO, MemberDO> subMemberJoin = root.join("subMember", JoinType.LEFT);
              list.add(criteriaBuilder.equal(subMemberJoin.get("source").as(Integer.class), source));
          }

          Predicate[] p = new Predicate[list.size()];
          return criteriaBuilder.and(list.toArray(p));
        };

        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberDepositPageQueryVO queryVO = new MemberDepositPageQueryVO();
            queryVO.setValidateId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setRoleName(relationDO.getSubRole().getRoleName());
            queryVO.setSourceName(MemberRegisterSourceEnum.getCodeMessage(relationDO.getSubMember().getSource()));
            queryVO.setRegisterTime(relationDO.getCreateTime().format(ServiceConfig.DEFAULT_DATETIME_FORMATTER));
            queryVO.setInnerStatus(relationDO.getInnerStatus());
            queryVO.setInnerStatusName(MemberInnerStatusEnum.getCodeMsg(relationDO.getInnerStatus()));
            queryVO.setOuterStatus(relationDO.getOuterStatus());
            queryVO.setOuterStatusName(MemberOuterStatusEnum.getCodeMsg(relationDO.getOuterStatus()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 查询会员详细信息
     * @param validateId 审核内容Id
     * @param loginUser  登录用户
     * @return 查询结果
     */
    private Wrapper<MemberDepositDetailVO> getValidateMemberDetails(Long validateId, UserLoginCacheDTO loginUser) {
        MemberRelationDO relationDO = relationRepository.findById(validateId).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        if(relationDO.getValidateTask() == null || !StringUtils.hasLength(relationDO.getValidateTask().getProcessKey()) || !StringUtils.hasLength(relationDO.getValidateTask().getTaskId()) || !relationDO.getValidateTask().getProcessTypeEnum().equals(MemberProcessTypeEnum.MEMBER_DEPOSITORY.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MC_MEMBER_PROCESS_DATA_ERROR);
        }

        return getValidateMemberDetails(relationDO, loginUser);
    }

    /**
     * 查询“审核入库”（一级）和（二级）的会员详情
     * @param loginUser 登录用户
     * @param relationDO 会员关系
     * @return 查询结果
     */
    private Wrapper<MemberDepositGradeDetailVO> getDepositGradeDetails(UserLoginCacheDTO loginUser, MemberRelationDO relationDO) {
        Wrapper<MemberToClassifyDetailVO> result = getToClassifyDetails(loginUser, relationDO);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        MemberDepositGradeDetailVO detailVO = new MemberDepositGradeDetailVO();
        BeanUtils.copyProperties(result.getData(), detailVO);

        detailVO.setClassification(baseMemberClassificationService.getMemberClassification(relationDO));
        return Wrapper.success(detailVO);
    }

    /**
     * 查询“待入库分类”会员详情
     * @param loginUser 登录用户
     * @param relationDO 会员关系
     * @return 查询结果
     */
    private Wrapper<MemberToClassifyDetailVO> getToClassifyDetails(UserLoginCacheDTO loginUser, MemberRelationDO relationDO) {
        MemberInspectDO inspectDO = memberInspectRepository.findFirstByMemberIdAndRoleIdAndSubMemberAndSubRoleIdAndSource(loginUser.getMemberId(), loginUser.getMemberRoleId(), relationDO.getSubMember(), relationDO.getSubRoleId(), MemberInspectSourceEnum.BY_MEMBER_PROCESS.getCode());

        Wrapper<MemberDepositDetailVO> result = getValidateMemberDetails(relationDO, loginUser);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        MemberToClassifyDetailVO detailVO = new MemberToClassifyDetailVO();
        BeanUtils.copyProperties(result.getData(), detailVO);
        //在MemberToClassifyDetailVO的无参构造函数对字段做了初始化
        if(inspectDO != null) {
            MemberInspectVO inspectVO = new MemberInspectVO();
            inspectVO.setInspectDay(inspectDO.getInspectTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            inspectVO.setScore(ServiceConfig.BIG_DECIMAL_FORMAT.format(inspectDO.getScore()));
            inspectVO.setResult(StringUtils.hasLength(inspectDO.getResult()) ? inspectDO.getResult() : "");
            inspectVO.setReports(CollectionUtils.isEmpty(inspectDO.getReports()) ? new ArrayList<>() : inspectDO.getReports().stream().map(fileBO -> new FileVO(fileBO.getName(), fileBO.getUrl())).collect(Collectors.toList()));
            detailVO.setInspection(inspectVO);
        }

        detailVO.setPartnerTypes(MemberPartnerTypeEnum.toDropdownList());

        return Wrapper.success(detailVO);
    }

    /**
     * 查询会员详细信息
     * @param relationDO 会员关系
     * @param loginUser  登录用户
     * @return 查询结果
     */
    private Wrapper<MemberDepositDetailVO> getValidateMemberDetails(MemberRelationDO relationDO, UserLoginCacheDTO loginUser) {
        Wrapper<WorkflowTaskListBO> result = workflowFeignService.listMemberProcessSteps(loginUser.getMemberId(), relationDO.getValidateTask().getProcessKey(), relationDO.getValidateTask().getTaskId());
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        MemberDepositDetailVO detailVO = new MemberDepositDetailVO();
        detailVO.setOuterVerifySteps(baseMemberValidateService.getMemberDepositOuterSteps(loginUser.getMemberRoleName(), relationDO.getSubRoleName()));
        detailVO.setCurrentOuterStep(2);

        detailVO.setInnerVerifySteps(result.getData().getStepList());
        detailVO.setCurrentInnerStep(result.getData().getCurrentStep());

        detailVO.setValidateId(relationDO.getId());
        detailVO.setMemberId(relationDO.getSubMemberId());
        detailVO.setName(relationDO.getSubMember().getName());
        detailVO.setOuterStatus(relationDO.getOuterStatus());
        detailVO.setOuterStatusName(MemberOuterStatusEnum.getCodeMsg(relationDO.getOuterStatus()));
        detailVO.setInnerStatus(relationDO.getInnerStatus());
        detailVO.setInnerStatusName(MemberInnerStatusEnum.getCodeMsg(relationDO.getInnerStatus()));
        detailVO.setStatus(relationDO.getStatus());
        detailVO.setStatusName(MemberStatusEnum.getCodeMessage(relationDO.getStatus()));
        detailVO.setMemberTypeEnum(relationDO.getSubMemberTypeEnum());
        detailVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubMemberTypeEnum()));
        detailVO.setRoleName(relationDO.getSubRoleName());
        detailVO.setLevel(relationDO.getLevelRight() == null ? 0 : relationDO.getLevelRight().getLevel());
        detailVO.setLevelTag(relationDO.getLevelRight() == null ? "" : relationDO.getLevelRight().getLevelTag());
        detailVO.setAccount(relationDO.getSubMember().getAccount());
        detailVO.setPhone(relationDO.getSubMember().getPhone());
        detailVO.setEmail(relationDO.getSubMember().getEmail());
        detailVO.setRegisterTime(relationDO.getCreateTime().format(ServiceConfig.DEFAULT_DATETIME_FORMATTER));
        //渠道信息
        if(relationDO.getSubMemberLevelTypeEnum().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
            if(relationDO.getChannel() == null) {
                return Wrapper.fail(ResponseCode.MC_MS_SUB_MEMBER_CHANNEL_DOES_NOT_EXIST);
            }

            detailVO.setChannelLevelTag(relationDO.getChannel().getChannelLevelTag());
            detailVO.setChannelTypeName(MemberChannelTypeEnum.getMsg(relationDO.getChannel().getChannelType().getChannelTypeEnum()));
            detailVO.setAreas(AgentAreaUtil.transferToList(relationDO.getChannel().getAgentArea()));
            detailVO.setRemark(StringUtils.hasLength(relationDO.getChannel().getRemark()) ? relationDO.getChannel().getRemark() : "");
        } else {
            detailVO.setChannelLevelTag("");
            detailVO.setChannelTypeName("");
            detailVO.setAreas(new ArrayList<>());
            detailVO.setRemark("");
        }

        //注册资料，由于会员入库流程之前必须是平台审核通过，而平台审核通过时注册资料的版本已经变为“Using"了，所以这里查询的版本是”Using"
        detailVO.setRegisterDetails(baseMemberRegisterDetailService.groupMemberRegisterDetailText(relationDO.getSubMember(), MemberDetailVersionEnum.USING));

        //入库资料
        detailVO.setDepositDetails(baseMemberDepositDetailService.mergeMemberDepositoryDetailText(relationDO));

        //资质证明
        detailVO.setQualities(baseMemberQualificationService.findMemberQualities(relationDO));

        //内、外部历史记录
        detailVO.setInnerHistory(baseMemberHistoryService.listMemberInnerHistory(relationDO));
        detailVO.setOuterHistory(baseMemberHistoryService.listMemberOuterHistory(relationDO));

        return Wrapper.success(detailVO);
    }
}
